<template>
	<view class="content">
		<!-- <view style="margin-top: var(--status-bar-height);"></view> -->
		<view class="main">
			<top-bar>
				<template #left>
					<image :src="userProfile" class="tab-left-image" mode="aspectFill" @tap="toDetail()"></image>
				</template>
				<template #center>
					<text style="font-size: 40rpx;">首页</text>
				</template>
				<template #right>
					<view style="width: 100vw;height: 100vh;position: fixed;top: 0;left: 0;" v-show="isShowMenu"
						@tap.stop="showMenu">
						<!-- 遮罩层 -->
					</view>
					<view @tap="showMenu">
						<view style="position: relative;">
							<image src="../../static/images/index/add.png" style="width: 48rpx;height: 48rpx;"></image>
						</view>
						<menu-list v-if="isShowMenu"></menu-list>
					</view>

				</template>

			</top-bar>
			<view class="friend-list" @tap="toReqList()">
				<!-- 好友请求列表 -->
				<view class="friend-list-l">
					<!-- s申请tip -->
					<text class="tip" v-show="friendApplyCountTip">{{friendApplyCountTip}}</text>
					<!-- 用户头像 -->
					<image src="../../static/images/index/apply.png" mode=""></image>
				</view>
				<view class="friend-list-r">
					<view class="top">
						<view class="name">好友请求</view>
						<view class="time">{{frinedLastSubmitTime}}</view>
					</view>
					<view class="news">{{frinedLastSubmitMsg}}</view>
				</view>
			</view>
			<view class="friend-list robot" @tap="toRobot()">
				<!-- 好友请求列表 -->
				<view class="friend-list-l">
					<!-- 用户头像 -->
					<image src="../../static/images/cheat/machine.png" mode=""></image>
				</view>
			</view>
			<!-- 好友聊天消息和群消息 -->
			<view class="friend">
				<view scroll-y="true" style="height: calc(100% - 128rpx);">
					<view class="friend-list" v-for="(item,index) in userList" :key="item.id"
						@tap="chat(item.id,index)">
						<view class="friend-list-l">
							<!-- 未读消息tip -->
							<text class="tip" v-if="item.tip">{{item.tip}}</text>
							<!-- 用户头像 -->
							<image :src="item.imgurl"></image>
						</view>
						<view class="friend-list-r">
							<view class="top">
								<view class="name">{{item.name}}</view>
								<view class="time">{{FormDataChat(item.lastTime)}}</view>
							</view>
							<view class="news">{{item.news}}</view>
						</view>
					</view>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import util from '../../commons/js/util.js'
	import {
		RuntimeServerUrl
	} from "../../commons/getRuntimeEnv.js"
	import tokenMatchApi from "../../api/tokenMatch.js"
	import TopBar from "../../components/top-bar/top-bar.vue"
	import MenuList from "../../components/menu-list/menu-list.vue"
	import {
		getUsetList,
		getUnread,
		clearUnreadMsgApi
	} from "../../api/getInfo.js"
	export default {
		data() {
			return {
				//登入之后显示用户id
				userProfile: '',
				userid: '',
				title: 'Hello',
				userList: [],
				//好友申请数
				friendApplyCountTip: 0,
				frinedLastSubmitTime: '',
				frinedLastSubmitMsg: '',
				cycleTimer: null,
				isShowMenu: false
			}
		},
		components: {
			TopBar,
			MenuList
		},
		onReady() {


		},
		//页面显示就会调用
		onShow() {
			this.getMyselfProfile()
			//如果本地有好友数据 就不需要去请求
			// console.log('看看onshow是什么时候执行呢');
			this.getFirendApplydata()
			let userInfo = uni.getStorageSync("userInfo")
			if (userInfo) {
				this.userProfile = userInfo.imgrul
			} else {
				this.getMyselfProfile()
			}
		},
		// 第一次加载使用this.friendApplyCountTip=applydata.length
		onLoad(option) {
			this.userid = uni.getStorageSync('userid')
			let userInfo = uni.getStorageSync("userInfo")
			console.log(userInfo, "user");
			if (userInfo) {
				this.userProfile = userInfo.imgrul
			} else {
				this.getMyselfProfile()
			}
			// 试着将socket链接挂载到root实例中 其他组件可以使用  
			// 进入主页才会链接socket服务
			// this.$socket.connect()
			this.match()
			if (option.id) {
				this.userid = option.id
			} else {
				this.userid = uni.getStorageSync('userid')
			}
			// 上传用户指定id，后端将其作为键，value为socketid
			// this.$socket.emit("registerUserid", this.userid)
			console.log(this.userid);

			this.$socket.on("loginSuccess", (msg) => {
				console.log(msg);
			})

			// 有人发消息过来时
			let that = this
			this.$socket.on("receivePrivateMsg", (msg) => {
				// 没有记录就新建一个
				let hitIndex = that.userList.findIndex(item => item.id == msg.fromId)
				console.log(hitIndex, "命中");
				//有记录就更新
				console.log(that.userList);
				if (hitIndex != -1) {
					this.userList[hitIndex].lastTime = new Date().getTime()
					this.userList[hitIndex].tip++
					if (msg.types == 1) {
						this.userList[hitIndex].news = '[图片]'
					} else if (msg.types == 2) {
						this.userList[hitIndex].news = '[语音]'
					} else if (msg.types == 3) {
						this.userList[hitIndex].news = '[位置]'
					} else {
						this.userList[hitIndex].news = msg.message
					}
				}
				console.log(msg, "接收到消息");
			})


		},


		onHide() {
			//离开当前页面清空计时器
			clearInterval(this.cycleTimer)
			this.cycleTimer = null
		},
		onUnload() {
			this.$socket.emit("loginOutUserid", this.userid)
			this.$socket.disconnect()
		},
		onPullDownRefresh() {
			let timer = setTimeout(async () => {
				this.match()
				this.getFirendApplydata()
				this.getMyselfProfile()
				// this.userList=await this.getdate()
				uni.stopPullDownRefresh();
				clearTimeout(timer)
				timer = null;
			}, 1000);
		},
		methods: {
			showMenu() {
				this.isShowMenu = !this.isShowMenu
				console.log("xianshi");
			},
			toDetail() {
				// console.log('garllery',id);
				uni.navigateTo({
					url: `/pages/userGarllery/userGarllery?id=${this.userid}`,

				})
			},
			//获取自己的头像
			getMyselfProfile() {
				util.request({
					url: "/user/detail",
					method: "POST",
					data: {
						id: this.userid
					}
				}).then(res => {
					//存用户详情星系 如果有数据就不用去发请求
					let userInfo = Object.assign({}, res.data.result, {
						imgrul: RuntimeServerUrl + res.data.result.imgrul
					})
					console.log(userInfo, "userinfo");
					uni.setStorageSync("userInfo", userInfo)
					this.userProfile = RuntimeServerUrl + res.data.result.imgrul
				})
			},
			//得到一个好友列表数组，包括头像 名称 最后一条消息，最后一条消息的时间
			async getdate() {
				let userlist = await util.request({
					url: '/index/getUserList',
					method: "POST",
					data: {
						uid: this.userid,
						state: 0
					}
				})

				//处理得到的好友列表信息
				userlist.data.result.forEach(async (item) => {
					item.imgurl = `${RuntimeServerUrl}${item.imgurl}`
					console.log(item.imgurl);
					this.$set(item, 'news')
					this.$set(item, 'tip')
					//获取最后一条消息信息
					let lastmsg = await this.getLastMsg(item.id) || {}

					if (lastmsg.type == "1") {
						item['news'] = '[图片]'
					} else if (lastmsg.type == "2") {
						item['news'] = '[语音]'
					} else if (lastmsg.type == "3") {
						item['news'] = '[位置]'
					} else {
						item['news'] = lastmsg.message
					}

					// item['news']=lastmsg.message
					//formatDate 接收一个时间戳
					item['lastTime'] = new Date(lastmsg.time).getTime()
					item.type = lastmsg.type
					//获取未读消息数
					item.tip = await getUnread(this.userid, item.id)
					// console.log(item);
				})

				// this.userList=userlist.data.result
				return Promise.resolve(userlist.data.result)
			},

			// 好友id获取最后一条聊天信息
			getLastMsg(fid) {
				return new Promise((resolve, reject) => {
					util.request({
						url: "/index/getlastmessage_u",
						method: "POST",
						data: {
							uid: this.userid,
							fid: fid
						}
					}).then(res => {
						//返回请求得到的最后消息信息
						resolve(res.data.result)
					}).catch(err => {
						console.log(err);
					})
				})
			},


			async getFirendApplydata() {
				let applydata = await this.getFirendApplyCount()
				// console.log(applydata);
				if (applydata.length != 0) {
					// console.log('不执行？？');
					this.friendApplyCountTip = applydata.length
					this.frinedLastSubmitTime = util.formatDate(new Date(applydata[0].lastTime))
					this.frinedLastSubmitMsg = applydata[0].name ? applydata[0].name + '请求添加为好友' : ''
				} else {
					//没有好友申请，显示空数据等
					this.friendApplyCountTip = 0
					this.frinedLastSubmitTime = null
					this.frinedLastSubmitMsg = null
				}
			},

			//获取申请添加好友信息 =>数组
			getFirendApplyCount() {
				return new Promise((resolve, reject) => {
					util.request({
						url: "/index/getUserList",
						method: "POST",
						data: {
							uid: this.userid,
							//查询与自己有关的好友 state 0表示好友 2表示申请中
							state: 2
						}
					}).then(res => {
						//返回请求得到的最后消息信息 有长度才返回数组
						if (res.data.result.length) {
							resolve(res.data.result)
							// console.log(res.data.result.length);
						} else {
							resolve([])
						}
						// console.log(res.data.result.length,"请求条数");
					}).catch(err => {
						console.log(err);
					})
				})
			},

			//登入加载同时，向socket服务器发送uid
			join(uid) {
				// console.log(this.socket);
				this.socket.emit("user login", uid)
			},
			// 用户socket，接受消息时刷新页面
			socketMsgAdnPushShow() {
				this.socket.on("receive", ({
					message,
					types,
					imgurl
				}, fromId) => {
					console.log(message, types, fromId);
					console.log(this.userList);
					// 根据id找到对应的用户
					this.userList.forEach(item => {
						//先保存消息数据，然后
						if (item.id == fromId) {
							item.tip++
							if (types == 1) {
								item.news = '[图片]'
							} else if (types == 2) {
								item.news = '[语音]'
							} else if (types == 3) {
								item.news = '[位置]'
							} else {
								item.news = message
							}
							item.lastTime = new Date().getTime()
						}
						console.log(item, '好友消息列表');
					})
					this.userList.sort((a, b) => {
						return b.lastTime - a.lastTime;
					})

				})
			},
			//比较验证token
			match() {
				tokenMatchApi().then(async res => {
					//页面加载时需要对token进行匹配 无效就会跳转到登入页
					// console.log(res.data.result);//1匹配成功
					if (res.data.result) {
						this.userList = await this.getdate()
					} else if (!res.data.result) {
						uni.showToast({
							title: "登入信息过期 请重新登入",
							icon: "none",
							duration: 1500,
							success() {
								setTimeout(() => {
									uni.redirectTo({
										url: "/pages/login/login"
									})
								}, 1500)
							}
						})

					}
				})
			},
			//格式化时间
			FormDataChat(e) {
				return util.formatDate(new Date(e), 1)
			},

			chat(id, index) {
				uni.navigateTo({
					url: `/pages/cheat/cheat?id=${id}`
				})
				// 传入选中的下标 在用户点击进入时清除
				this.userList[index].tip = 0
				clearUnreadMsgApi(this.userid, id).then(res => {
					console.log("清空未读消,成功");
				}).catch(err => {
					throw new Error(err)
				})
			},
			//好友申请列表 必要的参数需要使用
			toReqList() {
				uni.navigateTo({
					url: `/pages/friendrequest/friendrequest?id=${this.userid}`
				})
			},
			toRobot() {
				uni.navigateTo({
					url: "/pages/assistant/assistant"
				})
			},
			toGarllery(id) {
				uni.navigateTo({
					url: `/pages/detail/detail?id=${id}`
				})
			}

		}
	}
</script>

<style lang='scss'>
	/* scss中使用@import导入样式 */

	/* 顶栏部分 */
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100vh;
		width: 100vw;
	}

	/* 好友展示部分 */
	.main {
		box-sizing: border-box;
		background-color: $uni-bg-color;
		width: 100%;
		height: calc(100% - var(--status-bar-height) - var(--status-bar-height) - 44px);
		/* padding: 0 ; */
		/* border: 1px solid red; */
		margin-top: 88rpx;
		/* padding: 20rpx; */
		position: absolute;
		top: var(--status-bar-height);

		.friend {
			height: calc(100% - var(--status-bar-height) - var(--status-bar-height) - 44px - 128rpx);
		}

		.robot {
			position: fixed;
			bottom: 40rpx;
			right: 40rpx;
			z-index: 9;
		}

		.friend-list {
			display: flex;
			/* 水平垂直居中 */
			justify-content: center;
			align-items: center;
			/* border: 1px solid red; */
			/* margin: 20rpx 0 20rpx 0; */
			height: 128rpx;

			.friend-list-l {
				position: relative;

				/* width: 21%; */
				image {
					height: $uni-img-size-base;
					width: $uni-img-size-base;
					margin-top: 8rpx;
					border-radius: $uni-border-radius-base;
					background-color: $uni-color-primary;
				}

				.tip {
					width: 36rpx;
					height: 36rpx;
					text-align: center;
					font-size: 24rpx;
					color: $uni-bg-color;
					letter-spacing: -0.41px;
					font-weight: 400;
					position: absolute;
					top: -0rpx;
					right: -8rpx;
					background-color: #FF5D5B;
					border-radius: 50%;
					z-index: 10;
				}
			}

			.friend-list-r {
				width: 79%;
				display: flex;
				/* border: 1px solid red; */
				flex-direction: column;

				.top {
					display: flex;
					justify-content: space-between;
					margin-left: 18rpx;

					/* border: 1px solid red; */
					.name {
						height: 50rpx;
						font-size: 36rpx;
						color: #272832;
						letter-spacing: -0.62px;
						line-height: 50rpx;
					}

					.time {
						height: 34rpx;
						font-size: 24rpx;
						color: rgba(39, 40, 50, 0.40);
						letter-spacing: -0.41px;
						line-height: 50rpx;
						/* margin-top: 5rpx; */
					}
				}

				.news {
					width: 95%;
					line-height: 40rpx;
					align-items: flex-start;

					/* 超出内容使用...隐藏 */
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 1;
					overflow: hidden;

					font-size: $uni-font-size-sm;
					color: rgba(39, 40, 50, 0.60);
					letter-spacing: -0.48rpx;
					font-weight: 400;
					margin: 0 18rpx 0 18rpx;
				}
			}
		}
	}

	.top-bar-left-img {
		box-shadow: 1rpx 1rpx 4px #ffed47;
	}

	/* 	.friend-list:focus{
		background-color: $uni-bg-color-hover;
	} */
	@media only screen and (min-width:812px) {
		.content {
			height: 1624rpx;
			width: 750rpx;
		}
	}

	.tab-left-image {
		width: 68rpx;
		height: 68rpx;
		border-radius: 16rpx;
	}

	.menu {
		position: absolute;
		top: 70rpx;
		left: -150rpx;
		width: 200rpx;
		border-radius: 8rpx;
		background-color: #ffed47;

		.list {
			width: 100%;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			font-size: 28rpx;

			.list-item {
				text-align: center;
				height: 44rpx;
				padding: 8rpx;

				&:not(:last-child) {
					border-bottom: 2rpx solid #a88d8d;
				}

			}
		}

		&::after {
			content: "";
			display: block;
			width: 0px;
			height: 0px;
			position: absolute;
			left: 140rpx;
			top: -50rpx;
			z-index: -1;
			border-bottom: 30rpx solid #0f0f32;
			border-top: 30rpx solid transparent;
			border-right: 30rpx solid transparent;
			border-left: 30rpx solid transparent;
		}
	}
</style>